const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

function getRandomRangeInt(min, max) {
  min = Math.ceil(min); // 确保min是整数
  max = Math.floor(max); // 确保max是整数
  return Math.floor(Math.random() * (max - min + 1)) + min; // 返回介于min和max之间的整数
}

function getRandomString(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return result;
}

function getRandomNumString(length) {
  if (!Number.isInteger(length) || length < 1) {
    throw new Error('Length must be a positive integer');
  }
  const first = Math.floor(Math.random() * 9 + 1); // 首位1-9
  const rest = Array.from({ length: length - 1 }, () => Math.floor(Math.random() * 10));
  return first + rest.join('');
}

const getRandomLatLon = (centerLat, centerLon, radiusInKm) => {
  const earthRadiusInKm = 6371; // 地球半径，单位为km
  const deltaLatitude = radiusInKm / earthRadiusInKm * (180 / Math.PI); // 纬度范围修正
  const deltaLongitude = radiusInKm / (earthRadiusInKm * Math.cos(centerLat * (Math.PI / 180))) * (180 / Math.PI); // 经度范围修正
  const randomLatitude = centerLat + (Math.random() - 0.5) * deltaLatitude;
  const randomLongitude = centerLon + (Math.random() - 0.5) * deltaLongitude;
  return {
    latitude: randomLatitude,
    longitude: randomLongitude
  };
}

function getRandomZhChars(length) {
  let arr = []
  for (let i = 0; i < length; i++) {
    let str
    //汉字对应的unicode编码为u4e00-u9fa5转为10进制为19968-40869，先取随机数，再转为16进制
    str = '\\u' + (Math.floor(Math.random() * (40869 - 19968)) + 19968).toString(16)
    //在用正则操作数据后进行解码。注意：unescape() 函数在 JavaScript 1.5 版中已弃用。请使用 decodeURI() 或 decodeURIComponent() 代替。
    str = unescape(str.replace(/\\u/g, "%u"));
    arr.push(str)
  }
  let chinese = arr.join("")
  return chinese
}

function getRandomItem(array) {
  return array[Math.floor(Math.random() * array.length)];
}

module.exports = {
  formatTime,
  getRandomRangeInt,
  getRandomString,
  getRandomNumString,
  getRandomLatLon,
  getRandomZhChars,
  getRandomItem
}